package com.yundasys.lab04springbootlocalmsg.service.impl;

import com.yundasys.lab04springbootlocalmsg.dao.PaymentMsgDao;
import com.yundasys.lab04springbootlocalmsg.entity.PaymentMsg;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @PACKAGE_NAME: com.yundasys.lab04springbootlocalmsg.service.impl
 * @NAME: OrderScheduler
 * @USER: jiangta
 * @DATE: 2021/1/14
 * @TIME: 9:35 下午
 * @PROJECT_NAME: springboot-labs
 */
@Service
public class OrderScheduler {

    @Autowired
    PaymentMsgDao paymentMsgDao;

    @Scheduled(cron = "0/10 * * * * ?")
    public void orderNotify() throws Exception {

        PaymentMsg paymentMsg = new PaymentMsg();
        paymentMsg.setStatus(0);
        List<PaymentMsg> paymentMsgs = paymentMsgDao.queryAll(paymentMsg);
        if(CollectionUtils.isEmpty(paymentMsgs)) return;

        for(PaymentMsg paymentMsg1 : paymentMsgs) {
            Integer orderId = paymentMsg1.getOrderId();

            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost httpPost = new HttpPost("http://localhost:8080/handleOrder");
            NameValuePair orderIdPair = new BasicNameValuePair("orderId",orderId+"");
            List<NameValuePair> nameValuePairs = new ArrayList<>();
            nameValuePairs.add(orderIdPair);
            HttpEntity httpEntity = new UrlEncodedFormEntity(nameValuePairs);
            httpPost.setEntity(httpEntity);
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            String s = EntityUtils.toString(httpResponse.getEntity());

            if("success".equals(s)){
                paymentMsg1.setStatus(1);
                paymentMsg1.setUpdateUser(0);
                paymentMsg1.setUpdateTime(new Date());
                paymentMsgDao.update(paymentMsg1);
            } else {
                Integer failureCnt = paymentMsg1.getFailureCnt();
                failureCnt++;
                if(failureCnt >5){
                    paymentMsg1.setStatus(2);
                    paymentMsg1.setUpdateUser(0);
                    paymentMsg1.setUpdateTime(new Date());
                    paymentMsgDao.update(paymentMsg1);
                }
            }
        }

    }
}
